package com.zwj.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zwj.bo.*;
import com.zwj.dto.SelectClassQuery;
import com.zwj.dto.SelectStudentQuery;
import com.zwj.entity.ClassInfoEntity;
import com.zwj.entity.ClassStudentInfoEntity;
import com.zwj.entity.TeamMemberInfoEntity;
import com.zwj.entity.UserEntity;
import com.zwj.enums.*;
import com.zwj.mapper.ClassInfoMapper;
import com.zwj.mapper.CommonMapper;
import com.zwj.mapper.TeamMapper;
import com.zwj.mapper.UserMapper;
import com.zwj.service.ClassInfoService;
import com.zwj.utils.DataCheckUtils;
import com.zwj.utils.DateUtils;
import com.zwj.utils.PaginationUtils;
import com.zwj.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * <p>
 * 班级信息表 服务实现类
 * </p>
 *
 * @author zwj
 * @since 2021-07-21
 */
@Service
public class ClassInfoServiceImpl  implements ClassInfoService {
    private final TeamMapper teamMapper;
    private final CommonMapper commonMapper;
    private final UserMapper userMapper;
    private final ClassInfoMapper classInfoMapper;
    public ClassInfoServiceImpl(CommonMapper commonMapper,ClassInfoMapper classInfoMapper,UserMapper userMapper,TeamMapper teamMapper) {
        this.commonMapper = commonMapper;
        this.classInfoMapper = classInfoMapper;
        this.userMapper = userMapper;
        this.teamMapper = teamMapper;
    }
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result  addClass(AddClassBo addClassBo, UserEntity userEntity) {
        //数据校验
        DataCheckUtils.isNotBlank(addClassBo.getCollegesId(), "院系ID不能为空!");
        DataCheckUtils.isNotBlank(addClassBo.getClassBaseInfoId(), "班号ID不能为空!");
        DataCheckUtils.isNotBlank(addClassBo.getIsGraduation(), "是否结业不能为空!");
        DataCheckUtils.isNotBlank(addClassBo.getTeacherId(), "班主任ID不能为空!");
        DataCheckUtils.isNotBlank(addClassBo.getMajorId(), "专业ID不能为空!");
        DataCheckUtils.isNotBlank(addClassBo.getYearInfoId(), "年级ID不能为空!");
        DataCheckUtils.isValid(YesOrNoEnum.getEnumValue(addClassBo.getIsGraduation()) != null,"是否结业的状态值不存在");
        DataCheckUtils.isNotBlank(commonMapper.getClassBaseNameById(addClassBo.getClassBaseInfoId()), "班号ID不存在!");
        DataCheckUtils.isNotBlank(commonMapper.getMajorNameById(addClassBo.getMajorId()), "专业ID不存在!");
        DataCheckUtils.isNotBlank(commonMapper.getYearInfoNameById(addClassBo.getYearInfoId()), "年级ID不存在!");
        DataCheckUtils.isNotBlank(commonMapper.getTeacherNameById(addClassBo.getTeacherId()), "教师ID不存在!");
        DataCheckUtils.isNotBlank(commonMapper.getCollegesNameById(addClassBo.getCollegesId()), "院系ID不存在!");

        ClassInfoEntity classInfoEntity = classInfoMapper.getClassInfo(addClassBo);
        if(classInfoEntity!=null){
            return Result.error("班级信息重复");
        }
        //插入数据
        ClassInfoEntity classInfoEntity1 = new ClassInfoEntity();
        classInfoEntity1.setClassBaseInfoId(addClassBo.getClassBaseInfoId());
        classInfoEntity1.setMajorId(addClassBo.getMajorId());
        classInfoEntity1.setYearInfoId(addClassBo.getYearInfoId());
        classInfoEntity1.setCollegesId(addClassBo.getCollegesId());
        classInfoEntity1.setTeacherId(addClassBo.getTeacherId());
        classInfoEntity1.setIsGraduation(addClassBo.getIsGraduation());
        classInfoEntity1.setCreateBy(userEntity.getId());
        classInfoEntity1.setCreateTime(DateUtils.getCurrentTime());
        classInfoEntity1.setUpdateBy(userEntity.getId());
        classInfoEntity1.setUpdateTime(DateUtils.getCurrentTime());
        int row = classInfoMapper.insert(classInfoEntity1);
        //判断插入结果
        if (row == 0) {
            return Result.error("班级教师失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result updateClass(UpdateClassBo updateClassBo, UserEntity userEntity) {
        DataCheckUtils.isNotBlank(updateClassBo.getCollegesId(), "院系ID不能为空!");
        DataCheckUtils.isNotBlank(updateClassBo.getClassBaseInfoId(), "班号ID不能为空!");
        DataCheckUtils.isNotBlank(updateClassBo.getIsGraduation(), "是否结业不能为空!");
        DataCheckUtils.isNotBlank(updateClassBo.getTeacherId(), "班主任ID不能为空!");
        DataCheckUtils.isNotBlank(updateClassBo.getMajorId(), "专业ID不能为空!");
        DataCheckUtils.isNotBlank(updateClassBo.getYearInfoId(), "年级ID不能为空!");
        DataCheckUtils.isValid(YesOrNoEnum.getEnumValue(updateClassBo.getIsGraduation()) != null,"是否结业的状态值不存在");
        DataCheckUtils.isNotBlank(commonMapper.getClassBaseNameById(updateClassBo.getClassBaseInfoId()), "班号ID不存在!");
        DataCheckUtils.isNotBlank(commonMapper.getMajorNameById(updateClassBo.getMajorId()), "专业ID不存在!");
        DataCheckUtils.isNotBlank(commonMapper.getYearInfoNameById(updateClassBo.getYearInfoId()), "年级ID不存在!");
        DataCheckUtils.isNotBlank(commonMapper.getTeacherNameById(updateClassBo.getTeacherId()), "教师ID不存在!");
        DataCheckUtils.isNotBlank(commonMapper.getCollegesNameById(updateClassBo.getCollegesId()), "院系ID不存在!");

        //指定
        QueryWrapper<ClassInfoEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(ClassInfoEntity::getId, updateClassBo.getId());
        ClassInfoEntity classInfoEntity = classInfoMapper.selectOne(sectionQueryWrapper);
        if (classInfoEntity == null) {
            return Result.error("未找到该班级");
        }

        ClassInfoEntity classInfoEntity1 = classInfoMapper.getClassInfo1(updateClassBo);
        if(classInfoEntity1!=null){
            return Result.error("班级信息重复");
        }
        ClassInfoEntity classInfoEntity2 = new ClassInfoEntity();
        classInfoEntity2.setClassBaseInfoId(updateClassBo.getClassBaseInfoId());
        classInfoEntity2.setMajorId(updateClassBo.getMajorId());
        classInfoEntity2.setYearInfoId(updateClassBo.getYearInfoId());
        classInfoEntity2.setCollegesId(updateClassBo.getCollegesId());
        classInfoEntity2.setTeacherId(updateClassBo.getTeacherId());
        classInfoEntity2.setIsGraduation(updateClassBo.getIsGraduation());
        classInfoEntity2.setUpdateBy(userEntity.getId());
        classInfoEntity2.setUpdateTime(DateUtils.getCurrentTime());
        UpdateWrapper<ClassInfoEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(ClassInfoEntity::getId, updateClassBo.getId());
        int row = classInfoMapper.update(classInfoEntity2, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error("编辑班级信息失败");
        }
        return Result.success();
    }
    @Override
    public Result selectClass(SelectClassBo selectClassBo, String id) {
        int number = 1;
        int page = 1;
        if(id==null){
            number = selectClassBo.getNumber();
            page = selectClassBo.getPage();
            //分页参数是否正确
            DataCheckUtils.isValid(PaginationUtils.isPagingParameters(number, page), "分页参数错误!");
        }
        //查询项目组评分 mybatis
        List<Object> result = classInfoMapper.selectClass(new SelectClassQuery(PaginationUtils.getPageIndex(page, number),number, id, selectClassBo.getCollegesId(),selectClassBo.getMajorId(),selectClassBo.getYearInfoId(),selectClassBo.getClassBaseInfoId(),selectClassBo.getTeacherName(),selectClassBo.getIsGraduation()));
        if(id!=null) {
            int sum = ((List<Integer>) result.get(1)).get(0);
            if(sum==0){
                return Result.error("班级不存在");
            }
            return  Result.success(((List<SelectClassVo>) result.get(0)).get(0));
        }
        int sum = ((List<Integer>) result.get(1)).get(0);
        List<SelectClassVo> ClassVos = (List<SelectClassVo>) result.get(0);
        PaginationDate paginationDate = PaginationUtils.getPaginationDate(number, page, sum);
        //记录总数为0
        if (sum == 0) {
            SelectClassVo selectClassVo = new SelectClassVo();
            ClassVos.add(selectClassVo);
            return Result.success(new QueryReturnDate(paginationDate, ClassVos));
        }
        //当前页大于总页数
        if (PaginationUtils.isValid(paginationDate))
            return Result.error("当前页大于总页数");

        return Result.success(new QueryReturnDate(paginationDate, ClassVos));
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result addStudent(StudentBo studentBo, UserEntity userEntity) {
        //数据校验
        DataCheckUtils.isNotBlank(studentBo.getId(), "班级ID不能为空!");
        DataCheckUtils.isNotBlank(studentBo.getName(), "学生姓名不能为空!");
        DataCheckUtils.isValid(studentBo.getEmail().matches("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$"), "邮箱格式错误!");
        DataCheckUtils.isValid(studentBo.getUserNo().matches("[0-9]{6,16}"), "学号必须为6到16位之间!");
        DataCheckUtils.isValid(studentBo.getIdNo().matches("[0-9]{18}"), "身份证号格式错误!");
        DataCheckUtils.isNotBlank(studentBo.getSex(), "性别不能为空!");
        DataCheckUtils.isValid(SexEnum.getEnumValue(studentBo.getSex()) != null, "性别类型不存在!");
        DataCheckUtils.isValid(studentBo.getMobileNo().matches("^1[3|4|5|7|8][0-9]{9}$"), "手机号码格式错误!");
        DataCheckUtils.isNotBlank(studentBo.getPosition(), "项目角色不能为空!");
        DataCheckUtils.isValid(StudentPositionEnum.getEnumValue(studentBo.getPosition()) != null, "项目角色不存在");
        //查询指定工号、身份证号、手机号是否重复、邮箱
        QueryWrapper<UserEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(UserEntity::getUserNo, studentBo.getUserNo())
                .or().eq(UserEntity::getMobileNo, studentBo.getMobileNo())
                .or().eq(UserEntity::getIdNo, studentBo.getIdNo()).or().eq(UserEntity::getEmail, studentBo.getEmail()).select(UserEntity::getUserNo, UserEntity::getIdNo, UserEntity::getMobileNo,UserEntity::getEmail);
        List<UserEntity> users = userMapper.selectList(sectionQueryWrapper);
        //判断查询结果
        if (users.size() != 0) {
            for (UserEntity user : users) {
                DataCheckUtils.isNotValid(user.getUserNo().equals(studentBo.getUserNo()), "工号已存在");
                DataCheckUtils.isNotValid(user.getMobileNo().equals(studentBo.getMobileNo()), "手机号已存在");
                DataCheckUtils.isNotValid(user.getIdNo().equals(studentBo.getIdNo()), "身份证号已存在");
                DataCheckUtils.isNotValid(user.getEmail().equals(studentBo.getEmail()), "邮箱已存在");
            }
        }
        ClassInfoEntity classInfoEntity = classInfoMapper.selectById(studentBo.getId());
        if(classInfoEntity==null){
            return Result.error("班级不存在");
        }

        //插入数据
        UserEntity user = new UserEntity();
        user.setName(studentBo.getName());
        user.setUserNo(studentBo.getUserNo());
        user.setIdNo(studentBo.getIdNo());
        user.setSex(studentBo.getSex());
        user.setMobileNo(studentBo.getMobileNo());
        user.setPosition(studentBo.getPosition());
        user.setEmail(studentBo.getEmail());
        user.setDelFlag(ValidEnum.EFFECTIVE.getKey());
        user.setRoleType(RoleTypeEnum.STUDENT.getKey());
        user.setPassword(studentBo.getIdNo().substring(studentBo.getIdNo().length() - 6));
        user.setCreateBy(userEntity.getId());
        user.setCreateTime(DateUtils.getCurrentTime());
        user.setUpdateBy(userEntity.getId());
        user.setUpdateTime(DateUtils.getCurrentTime());

        int row = classInfoMapper.addStudent(user);
        //判断插入结果
        if (row == 0) {
            return Result.error("添加学生失败");
        }
        ClassStudentInfoEntity classStudentInfoEntity = new ClassStudentInfoEntity();
        classStudentInfoEntity.setStudentId(user.getId());
        classStudentInfoEntity.setClassInfoId(studentBo.getId());
        classStudentInfoEntity.setCreateBy(userEntity.getId());
        classStudentInfoEntity.setCreateTime(DateUtils.getCurrentTime());
        classStudentInfoEntity.setUpdateBy(userEntity.getId());
        classStudentInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        classStudentInfoEntity.setDelFlag(ValidEnum.EFFECTIVE.getKey());
        int  number =  classInfoMapper.addClassStudent(classStudentInfoEntity);
        if(number ==0){
            return  Result.error("添加到班级失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result updateStudent(StudentBo studentBo, UserEntity userEntity) {
        //数据校验
        DataCheckUtils.isNotBlank(studentBo.getStudentId(), "学生ID不能为空!");
        DataCheckUtils.isNotBlank(studentBo.getName(), "学生姓名不能为空!");
        DataCheckUtils.isValid(studentBo.getEmail().matches("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$"), "邮箱格式错误!");
        DataCheckUtils.isValid(studentBo.getUserNo().matches("[0-9]{6,16}"), "学号必须为6到16位之间!");
        DataCheckUtils.isValid(studentBo.getIdNo().matches("[0-9]{18}"), "身份证号格式错误!");
        DataCheckUtils.isNotBlank(studentBo.getSex(), "性别不能为空!");
        DataCheckUtils.isValid(SexEnum.getEnumValue(studentBo.getSex()) != null, "性别类型不存在!");
        DataCheckUtils.isValid(studentBo.getMobileNo().matches("^1[3|4|5|7|8][0-9]{9}$"), "手机号码格式错误!");
        DataCheckUtils.isNotBlank(studentBo.getPosition(), "项目角色不能为空!");
        DataCheckUtils.isValid(StudentPositionEnum.getEnumValue(studentBo.getPosition()) != null, "项目角色不存在");
        //指定ID查询教师
        QueryWrapper<UserEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(UserEntity::getId, studentBo.getStudentId()).eq(UserEntity::getRoleType,RoleTypeEnum.STUDENT.getKey())
                .select(UserEntity::getUserNo, UserEntity::getIdNo, UserEntity::getMobileNo,UserEntity::getIsFirstLogin,UserEntity::getEmail);
        UserEntity user = userMapper.selectOne(sectionQueryWrapper);
        if (user == null) {
            return Result.error("未找到该学生");
        }
        //查询指定工号、身份证号、手机号是否重复
        QueryWrapper<UserEntity> sectionQueryWrapper1 = new QueryWrapper<>();
        sectionQueryWrapper1.lambda().eq(UserEntity::getUserNo, studentBo.getUserNo())
                .or().eq(UserEntity::getMobileNo, studentBo.getMobileNo())
                .or().eq(UserEntity::getIdNo, studentBo.getIdNo()).or().eq(UserEntity::getEmail, studentBo.getEmail()).select(UserEntity::getUserNo, UserEntity::getIdNo, UserEntity::getMobileNo,UserEntity::getEmail);
        List<UserEntity> users = userMapper.selectList(sectionQueryWrapper1);
        String userNo = studentBo.getUserNo();
        String mobileNo = studentBo.getMobileNo();
        String idNo = studentBo.getIdNo();
        String email = studentBo.getEmail();
        //判断查询结果
        if (users.size() != 0) {
            for (UserEntity user1 : users) {
                String userNo1 = user1.getUserNo();
                DataCheckUtils.isNotValid(userNo1.equals(userNo) && !userNo1.equals(user.getUserNo()), "工号已存在");
                String mobileNo1 = user1.getMobileNo();
                DataCheckUtils.isNotValid(mobileNo1.equals(mobileNo) && !mobileNo1.equals(user.getMobileNo()), "手机号已存在");
                String idNo1 = user1.getIdNo();
                DataCheckUtils.isNotValid(idNo1.equals(idNo) && !idNo1.equals(user.getIdNo()), "身份证号已存在");
                String email1 = user1.getEmail();
                DataCheckUtils.isNotValid(email1.equals(email) && !email1.equals(user.getEmail()), "邮箱已存在");
            }

        }
        UserEntity updateUser = new UserEntity();
        updateUser.setName(studentBo.getName());
        updateUser.setUserNo(studentBo.getUserNo());
        updateUser.setIdNo(studentBo.getIdNo());
        updateUser.setSex(studentBo.getSex());
        updateUser.setMobileNo(studentBo.getMobileNo());
        updateUser.setPosition(studentBo.getPosition());
        updateUser.setEmail(studentBo.getEmail());
        if(user.getIsFirstLogin().equals("1")){
            updateUser.setPassword(updateUser.getIdNo().substring(updateUser.getIdNo().length() - 6));
        }
        updateUser.setUpdateBy(userEntity.getId());
        updateUser.setUpdateTime(DateUtils.getCurrentTime());
        UpdateWrapper<UserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(UserEntity::getId, studentBo.getStudentId());
        int row = userMapper.update(updateUser, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error("编辑学生信息失败");
        }
        return Result.success();
    }


    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public synchronized Result deleteStudent(StudentById studentById, UserEntity userEntity) {
        DataCheckUtils.isNotBlank(studentById.getId(), "班级id不能为空!");
        DataCheckUtils.isNotBlank(studentById.getStuentId(), "学生不能为空!");
        String studentId =  classInfoMapper.selectClassStudent(studentById);
        if(studentId == null){
            return  Result.error("当前班级下不存在该学生");
        }
        UserEntity updateUser = new UserEntity();
        updateUser.setDelFlag(ValidEnum.INVALID.getKey());
        UpdateWrapper<UserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(UserEntity::getId, studentById.getStuentId());

        int row = userMapper.update(updateUser, updateWrapper);
        //判断修改结果
        if (row == 0) {
            return Result.error("删除学生失败");
        }
        ClassStudentInfoEntity classStudentInfoEntity = new ClassStudentInfoEntity();
        classStudentInfoEntity.setStudentId(studentById.getStuentId());
        classStudentInfoEntity.setClassInfoId(studentById.getId());
        classStudentInfoEntity.setDelFlag(ValidEnum.INVALID.getKey());
        classStudentInfoEntity.setUpdateBy(userEntity.getId());
        classStudentInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
        int row1 = classInfoMapper.deleteClassStudent(classStudentInfoEntity);
        if (row1 == 0) {
            return Result.error("从班级删除学生失败");
        }
        String isGraduation =teamMapper.getTeamByStudentId(studentById.getStuentId());
        if(isGraduation!=null){
            if(isGraduation.equals(YesOrNoEnum.YES.getKey())){
                return Result.error("项目组已经结业，学生不能删除");
            }
            TeamMemberInfoEntity teamMemberInfoEntity = new TeamMemberInfoEntity();
            teamMemberInfoEntity.setUpdateBy(userEntity.getId());
            teamMemberInfoEntity.setUpdateTime(DateUtils.getCurrentTime());
            teamMemberInfoEntity.setDelFlag(ValidEnum.INVALID.getKey());
            teamMemberInfoEntity.setStudentId(studentById.getStuentId());
            if(teamMapper.deleteTeamStudentById(teamMemberInfoEntity)==0){
                return Result.error("从项目组删除学生失败");
            }
        }
        return Result.success();
    }

    @Override
    public Result selectStudent(SelectStudentBo selectStudentBo, StudentById studentById,int state) {
        int number = 1;
        int page = 1;
        if(state==1){
            number = selectStudentBo.getNumber();
            page = selectStudentBo.getPage();
            //分页参数是否正确
            DataCheckUtils.isValid(PaginationUtils.isPagingParameters(number, page), "分页参数错误!");
        }
        //查询项目组评分 mybatis
        List<Object> result = classInfoMapper.selectStudent(new SelectStudentQuery(PaginationUtils.getPageIndex(page, number),number, selectStudentBo.getId(), selectStudentBo.getUserNo(),selectStudentBo.getName(),selectStudentBo.getIdNo(),selectStudentBo.getSex(),selectStudentBo.getMobileNo(),selectStudentBo.getPosition(),selectStudentBo.getEmail(),studentById.getId(),studentById.getStuentId()));

        if(state==2) {
            int sum = ((List<Integer>) result.get(1)).get(0);
            if(sum==0){
                return Result.error("班级中不存在不存在该学生");
            }
            return  Result.success(((List<SelectStudentVo>) result.get(0)).get(0));
        }

        int sum = ((List<Integer>) result.get(1)).get(0);
        List<SelectStudentVo> selectStudentVos = (List<SelectStudentVo>) result.get(0);
        PaginationDate paginationDate = PaginationUtils.getPaginationDate(number, page, sum);
        //记录总数为0
        if (sum == 0) {
            SelectStudentVo selectStudentVo = new SelectStudentVo();
            selectStudentVos.add(selectStudentVo);
            return Result.success(new QueryReturnDate(paginationDate, selectStudentVos));
        }
        //当前页大于总页数
        if (PaginationUtils.isValid(paginationDate))
            return Result.error("当前页大于总页数");

        return Result.success(new QueryReturnDate(paginationDate, selectStudentVos));
    }

}
